package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.sql.CommonDataSource;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import com.sanqing.dao.Dao;
import com.sanqing.iframe.BookSearchFrame.TableListener;
import com.sanqing.model.BookInfo;
import com.sanqing.model.Borrow;
import com.sanqing.model.Item;
import com.sanqing.model.MapPz;
import com.sanqing.model.Operator;
import com.sanqing.model.common;

public class BorrowFrame extends JInternalFrame{
	private int Number=0;
	private final BorderLayout borderLayout;
	private final BorderLayout borderLayout_1;
	private final JScrollPane scrollPane;
	private final JPanel mainPanel;
	private final JPanel borrowSearchPanel;
	private final JPanel borrowPanel;
	private final GridLayout gridLayout;
	private final GridLayout gridLayout1;
	private final JLabel borrowLabel;
	private final JTextField borrowText;
	private final JButton searchButton;
	private final JButton deleteButton;
	private final JButton borrowButton;
	private final JButton closeButton;
	private  String borrowBookISBN;
	private int getSelectTableRow=-1;
	private static int canBorrowBook;
	private JTable table;
    private Object[][] results;
    private Object[][] Results;
    private String[] columnNames;
   
	private Map<String,Boolean>mapISBN=new HashMap<>();
	
	private Object[][] getFileStates(List list) {
	       String[] columnNames = {"图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格","图书数量","借阅日期"};
	       Object[][] results = new Object[list.size()][columnNames.length];
	       for (int i = 0; i < list.size(); i++) {
	           BookInfo bookinfo = (BookInfo) list.get(i);
	           results[i][0] = bookinfo.getISBN();
	           Integer typeId = bookinfo.getTypeid();
	           String bookTypeName = MapPz.getIdToName().get(typeId);
	           results[i][1] = bookTypeName;
	           results[i][2] = bookinfo.getBookname();
	           results[i][3] = bookinfo.getWriter();
	           results[i][4] = bookinfo.getTranslator();
	           results[i][5] = bookinfo.getPublisher();
	           results[i][6] = bookinfo.getDate();
	           results[i][7] = bookinfo.getPrice();
	           results[i][8] = bookinfo.getNumber();
	       }
	       return results;
	   }
	public BorrowFrame() {
       super();
       //Results=new Object[1][];
       
       borderLayout = new BorderLayout();
       getContentPane().setLayout(borderLayout);
       setIconifiable(true);
       setClosable(true);
       setTitle("借阅图书");
       setBounds(100, 100, 593, 406);
       mainPanel = new JPanel();
       borderLayout_1 = new BorderLayout();
       borderLayout_1.setVgap(5);
       mainPanel.setLayout(borderLayout_1);
       mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
       getContentPane().add(mainPanel);
       scrollPane = new JScrollPane();
       mainPanel.add(scrollPane);
       
       //
       borrowSearchPanel=new JPanel();
       mainPanel.add(borrowSearchPanel,BorderLayout.NORTH);
       gridLayout=new GridLayout(1,4);
       gridLayout.setHgap(0);
       borrowSearchPanel.setLayout(gridLayout);
       borrowLabel=new JLabel();
       borrowLabel.setText("图书的ISBN");
       borrowText=new JTextField();
       borrowText.setText("请输入要借阅书的ISBN");
       borrowText.addFocusListener(new borrowTextFocus());
       borrowText.addKeyListener(new borrowTextKey());
       searchButton=new JButton();
       searchButton.setText("添加");
       deleteButton=new JButton();
       deleteButton.setText("删除");
       searchButton.addActionListener(new searchButtonAction());
       deleteButton.addActionListener(new deleteButtonAction());
       borrowSearchPanel.add(borrowLabel);
       borrowSearchPanel.add(borrowText);
       borrowSearchPanel.add(searchButton);
       borrowSearchPanel.add(deleteButton);
       
       borrowPanel = new JPanel();
       mainPanel.add(borrowPanel,BorderLayout.SOUTH);
       gridLayout1=new GridLayout(1,2);
       borrowPanel.setLayout(gridLayout1);
       borrowButton=new JButton();
       closeButton =new JButton();
       borrowButton.setText("借阅");
       closeButton.setText("关闭");
       borrowButton.addActionListener(new borrowButtonAction());
       closeButton.addActionListener(new closeButtonAction() );
       borrowPanel.add(borrowButton);
       borrowPanel.add(closeButton);
       Init(common.UserName);
	}
	private class borrowTextKey implements KeyListener{

		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			if(borrowText.getText().length()>13)
			{
				borrowText.setText(borrowText.getText().substring(0, 13));
			}
			String a = borrowText.getText();
			for (int i = 0; i < a.length(); i++) {
				int b = a.charAt(i);
				if (!(b <= 57 && b >= 48)) {
					borrowText.setText("");
					break;
				}
			}
		}

		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			int temp = e.getKeyChar();
			if(borrowText.getText().length()==13)
			{
				e.consume();
			}
			else
			{
			if(temp==10) {}
			else if(temp!=46)
			{
				if(temp!=8)
				{
					if(temp>57)
					{
						e.consume();
					}
					else if(temp<48)
					{
						e.consume();
					}
				}
			}
			else
			{
				e.consume();
			}
		}
		}
		
	}
	
	private class borrowButtonAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
            if(Number==0)
            {
            	JOptionPane.showMessageDialog(null,"表格中尚未添加任何数据","提示",JOptionPane.WARNING_MESSAGE);
            }
            else if(getSelectTableRow!=-1)
            {
            	int addDate=0;
            	if(BookLoginIFrame.getOperator().getZj()==1) addDate=30;
            	else if(BookLoginIFrame.getOperator().getZj()==2)addDate=60;
            	else if(BookLoginIFrame.getOperator().getZj()==3)addDate=45;
            	DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
            	String borrowDate=dateTimeFormatter.format(LocalDate.now());
            	String backDate=dateTimeFormatter.format(LocalDate.now().plusDays(addDate));
            	Dao.InsertBorrow("insert into tb_borrow (readerISBN,bookISBN,isback,borrowDate,backDate)values('"+common.UserName+"','"+(String)Results[getSelectTableRow][0]+"',"+0+",'"+borrowDate+"','"+backDate+"')");
            	Dao.InsertBorrow("delete from tb_reserve where bookISBN='"+(String)Results[getSelectTableRow][0]+"' and readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"'");
            	deleteTableRecord();
            	JOptionPane.showMessageDialog(null,"借阅成功","提示",JOptionPane.PLAIN_MESSAGE);
            	borrowText.setText("请输入要借阅书的ISBN");
            }
            else
            {
            	int addDate=0;
            	if(BookLoginIFrame.getOperator().getZj()==1) addDate=30;
            	else if(BookLoginIFrame.getOperator().getZj()==2)addDate=60;
            	else if(BookLoginIFrame.getOperator().getZj()==3)addDate=45;
            	DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
            	String borrowDate=dateTimeFormatter.format(LocalDate.now());
            	String backDate=dateTimeFormatter.format(LocalDate.now().plusDays(addDate));
            	for(int i=0;i<Number;i++)
            	{
            		Dao.InsertBorrow("insert into tb_borrow (readerISBN,bookISBN,isback,borrowDate,backDate)values('"+BookLoginIFrame.getOperator().getISBN()+"','"+(String)Results[i][0]+"',"+0+",'"+borrowDate+"','"+backDate+"')");
            		Dao.InsertBorrow("delete from tb_reserve where bookISBN='"+(String)Results[i][0]+"' and readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"'");
            	}
            	Results=new Object[0][0];
            	results=new Object[0][0];
            	Number=0;
            	mapISBN=new HashMap<>();
            	tableE();
            	JOptionPane.showMessageDialog(null,"借阅成功","提示",JOptionPane.PLAIN_MESSAGE);
            	borrowText.setText("请输入要借阅书的ISBN");
            }
        	if(canBorrowBook==0)
     	    {
     	  		JOptionPane.showMessageDialog(null,"当前已是可借书的最大值","提示",JOptionPane.WARNING_MESSAGE);
     	  		doDefaultCloseAction();
     	    }
		}
	}
	private class closeButtonAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			doDefaultCloseAction();//关闭窗体
		}
		
	}
	
	private class deleteButtonAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			deleteTableRecord();
		}
		
	}
	
	private class searchButtonAction implements ActionListener{//查找并且添加

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			
			borrowBookISBN=borrowText.getText();
			results=getFileStates(Dao.selectBookInfo(borrowBookISBN));
			//System.out.println((int)results[0][8]);
			int borrowBookNumber=Dao.selectBorrow("select * from tb_borrow where bookISBN='"+borrowBookISBN+"' and isback=0").size()+Dao.selectReserve("select * from tb_reserve where bookISBN='"+borrowBookISBN+"'").size();
			//System.out.println(borrowBookNumber);
			int whetherBorrrowBook=Dao.selectBorrow("select * from tb_borrow where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"' and bookISBN='"+borrowBookISBN+"' and isback=0").size();
			int es=Dao.selectReserve("select * from tb_reserve where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"' and bookISBN='"+borrowBookISBN+"' and reserveDate IS NOT NULL").size();			boolean sf=true;
			int est=Dao.selectReserve("select * from tb_reserve where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"' and bookISBN='"+borrowBookISBN+"'").size();
			if(es>0) sf=false;
			System.out.println(canBorrowBook);
			
			if(results.length==0)
			{
				JOptionPane.showMessageDialog(null,"未找到这本图书","提示",JOptionPane.WARNING_MESSAGE);
			}
			else if(est==1&&sf)
			{
				JOptionPane.showMessageDialog(null,"该书已经预约","提示",JOptionPane.WARNING_MESSAGE);
			}
			else if(whetherBorrrowBook>=1)
			{
				JOptionPane.showMessageDialog(null,"这本书已经被借阅，且尚未归还","提示",JOptionPane.WARNING_MESSAGE);
			}
			else if(canBorrowBook==Number&&sf)
			{
				JOptionPane.showMessageDialog(null,"添加书籍加上已借阅书籍已到达最大借阅量","提示",JOptionPane.WARNING_MESSAGE);
			}
			else if(Objects.isNull(mapISBN.get(borrowBookISBN))==false)
			{
				JOptionPane.showMessageDialog(null,"该书已经添加到表格里面啦","提示",JOptionPane.WARNING_MESSAGE);
			}
			else if(borrowBookNumber>=(int)results[0][8]&&sf)
			{
				JOptionPane.showMessageDialog(null,"该书已全部被借阅,如有需求可以预约该书","提示",JOptionPane.WARNING_MESSAGE);
			}
			else
			{
				mapISBN.put(borrowBookISBN, true);
				Results=addResults();
				//System.out.println(Results.length);
				tableR();
			}
			borrowText.setText("请输入要借阅书的ISBN");
		}
	}
	
	private class TableListener implements MouseListener{

		@Override
		public void mouseClicked(MouseEvent arg0) {
			// TODO Auto-generated method stub
			getSelectTableRow=table.getSelectedRow();
		}

		@Override
		public void mouseEntered(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseExited(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mousePressed(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseReleased(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		
		
	}
	
	private class borrowTextFocus implements FocusListener{

		@Override
		public void focusGained(FocusEvent arg0) {
			// TODO Auto-generated method stub
			if(borrowText.getText().equals("请输入要借阅书的ISBN"))borrowText.setText("");
		}

		@Override
		public void focusLost(FocusEvent arg0) {
			// TODO Auto-generated method stub
			if(borrowText.getText().equals(""))borrowText.setText("请输入要借阅书的ISBN");
		}
		
	}
	private Object[][] addResults(){
		Object[][] Results;
		Number++;
		Results=new Object[Number][];
		for(int i=0;i<Number-1;i++)
			Results[i]=this.Results[i];
		Results[Number-1]=results[0];
		return Results;
	}
	private static boolean isTimeoutReturnBook(String username)
    {
    	DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
    	String nowDate=dateTimeFormatter.format(LocalDate.now());
    	int es=Dao.selectBookTimeout(username,nowDate).size();
    	if(es==0) return false;
    	return true;
    }
    private  void Init(String username)
    {
    	int hadBorrowBook=Dao.selectBorrow("select * from tb_borrow where readerISBN='"+username+"' and isback=0").size();
    	int maxBorrowBook=Integer.parseInt(Dao.selectOperator("select * from tb_operator where R_ISBN='"+username+"'").getMaxNum());
    	int set=Dao.selectReserve("select * from tb_reserve where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"'").size();

    	canBorrowBook=maxBorrowBook-hadBorrowBook-set;
    }
    
    private void tableR()
    {
		columnNames =new String[] {"图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格","图书数量"}; // 正确声明
		 table = new JTable(Results, columnNames) {
             @Override
             public boolean isCellEditable(int row, int column) {
                 return false; // 所有单元格都不可编辑
             }
         };
	    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	    scrollPane.setViewportView(table);
	    table.addMouseListener(new TableListener());
    }
    private void tableE()
    {
    	columnNames =new String[0] ; // 正确声明
    	 table = new JTable(Results, columnNames) {
             @Override
             public boolean isCellEditable(int row, int column) {
                 return false; // 所有单元格都不可编辑
             }
         };
	    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	    scrollPane.setViewportView(table);
	    table.addMouseListener(new TableListener());
    }
    private void deleteTableRecord()
    {
    	if(getSelectTableRow!=-1)
		{
    		Object[][] results=new Object[Number-1][];
			mapISBN.remove((String)Results[getSelectTableRow][0]);
			for(int i=0;i<getSelectTableRow;i++) results[i]=Results[i];
			for(int i=getSelectTableRow+1;i<Number;i++)
			{
				results[i-1]=Results[i];
			}
			Results=results;
			Number--;
			getSelectTableRow=-1;
			if(Number!=0)tableR();
			else 
			tableE();
			
		}
		else
		{
			JOptionPane.showMessageDialog(null,"未选择表中的数据或者表中没有数据","提示",JOptionPane.WARNING_MESSAGE);
		}
    }
}
